/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2016-12-13 23:28:02
 * @Description: 
 */
import 'isomorphic-fetch'

export default store => next => action => {
    console.log('api middleware action:', action);

    if (!action) {
        console.log('action is undefined');
        return;
    }

    const opt = action['API'];
    if (typeof opt === 'undefined') {
        return next(action)
    }

    let tmps = [],
        callback = () => {},
        data = opt.data;
    for (let key in data) {
        tmps.push(key + '=' + data[key]);
    }

    let fetchOptions = {
        method: 'POST',
        credentials: 'include', //cookie
        headers: {
            //'Accept': 'application/json',
            //'Content-Type': 'application/json'
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: tmps.join('&')
    };

    fetchOptions = opt.fetchOptions || fetchOptions;
    callback = opt.callback || callback;

    console.log('fetchRequest:', opt, fetchOptions, callback);

    fetch(opt.url, fetchOptions)
        .then((response) => {
            console.log('fetchResponse:', response);
            let responseData;
            try {
                responseData = response.json();
            } catch (err) {
                responseData = response;
            }
            return responseData;
        })
        .then((responseData) => {
            callback(next, responseData);
        })
        .catch((error) => {
            console.log(error);
        })

}
